from machine import RTC
from lib.config.index import device_config
from utils import device

device.running_ticks_us("lib.clock.rtc_clock.1")

class RTC_CLOCK:
    """
    RTC网络同步
    """

    def __init__(self):
        self.clock = RTC()
        self.datetime((1994, 10, 5, 1, 5, 45, 0, 0))

    def datetime(self, time_tuple=None):
        if not time_tuple:
            return self.clock.datetime()
        return self.clock.datetime(time_tuple)

    def get_subseconds(self):
        return self.get_datetime_fields("microsecond")

    def get_datetime_fields(self, field):
        (year, month, day, weekday, hour, minute, second, microsecond) = self.datetime()
        fields = {
            "year": year,
            "month": month,
            "day": day,
            "weekday": weekday,
            "hour": hour,
            "minute": minute,
            "second": second,
            "microsecond": microsecond,
        }
        if field in fields:
            return fields[field]
        return None

    def sync_network_time(self):
        from lib.net.index import http

        response = http.GET("http://www.hanxiaoxin.cn:8080/time")

        if device_config.is_debug():
            print("rtc sync network: ", response)

        if not response:
            return

        data = response["data"]
        year = data["year"]
        month = data["month"]
        weekday = data["weekday"]
        day = data["day"]
        hours = data["hours"]
        minutes = data["minutes"]
        seconds = data["seconds"]
        subseconds = data["subseconds"]
        time_tuple = (year, month, day, weekday, hours, minutes, seconds, subseconds)
        self.clock.datetime(time_tuple)
        # print("同步互联网时间:", time_tuple)

    def print_time(self):
        print(self.clock.datetime())

    def get_datetime(self):
        d = self.get_date_str()
        t = self.get_time_str()
        return f"{d} {t}"

    def get_date_str(self):
        (year, month, day, weekday, hour, minute, second, microsecond) = self.datetime()
        return f"{year}-{month}-{day}"

    def get_time_str(self):
        (year, month, day, weekday, hour, minute, second, microsecond) = self.datetime()
        h = "{:02}".format(hour)
        m = "{:02}".format(minute)
        s = "{:02}".format(second)
        return f"{h}:{m}:{s}"


clock = RTC_CLOCK()

device.running_ticks_us("lib.clock.rtc_clock.2")

if __name__ == "__main__":
    clock.sync_network_time()
    print(clock.datetime())
